package org.mc.wsdemo.java;
import java.sql.*;

//数据库工具类
public class JDBCUtils {
    //加载驱动，建立数据库连接
    public static Connection getConnection() throws SQLException,
            ClassNotFoundException{
        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql://localhost:3306/db_1";
        String username="root";
        String passwd="sql";
        Connection conn= DriverManager.getConnection(url, username, passwd);
        if (conn != null) {
            System.out.println("你已连接到数据库：" + conn.getCatalog());
        }
        return conn;
    }

    //关闭数据库连接，释放资源
    public static void release(PreparedStatement stmt, Connection conn) {
        if(stmt!=null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            stmt=null;
        }
        if(conn!=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            conn=null;
        }
    }
    //release函数重载
    public static void release(ResultSet rs, PreparedStatement stmt, Connection conn) {
        if(rs!=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            rs=null;
        }
        release(stmt, conn);
    }
    public String getdata() {
        String sql= "select * from system_data where Date='2024-04-06'";
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs=null;
        try {
            conn=getConnection();
            stmt=conn.prepareStatement(sql);
            rs = stmt.executeQuery(sql);
            if(rs.next())
            {
                String ret=new String(rs.getString(1)+rs.getString(2)+rs.getString(3));
                return ret;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            release(rs, stmt, conn);
        }
        return null;
    }
}
